<template>
  <div v-if="props.userRole !== 'admin'" class="no-permission">
    <h2>无权限访问医师管理</h2>
  </div>
  <div v-else class="doctor-management-container">
    <header class="doctor-header">
      <h2>医师管理</h2>
      <button class="add-btn" @click="openAddDialog">新增医师</button>
    </header>
    
    <!-- 消息提示 -->
    <div v-if="message" class="message" :class="{ 'success': messageType === 'success', 'error': messageType === 'error' }">
      {{ message }}
    </div>
    
    <div class="filter-bar">
      <input v-model="filter.name" placeholder="姓名" class="filter-input" />
      <select v-model="filter.gender" class="filter-select">
        <option value="">性别</option>
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
      <select v-model="filter.level" class="filter-select">
        <option value="">级别</option>
        <option value="实习医师">实习医师</option>
        <option value="住院医师">住院医师</option>
        <option value="主治医师">主治医师</option>
        <option value="副主任医师">副主任医师</option>
        <option value="主任医师">主任医师</option>
      </select>
      <select v-model="filter.category" class="filter-select">
        <option value="">诊治类别</option>
        <option v-for="cat in doctorCategories" :key="cat.id" :value="cat.category">{{ cat.category }}</option>
      </select>
      <button class="filter-btn" @click="applyFilter">查询</button>
      <button class="filter-btn" @click="resetFilter">重置</button>
    </div>
    <div class="doctor-table-scroll">
      <table class="doctor-table">
        <thead>
          <tr>
            <th>头像</th>
            <th>姓名</th>
            <th>年龄</th>
            <th>性别</th>
            <th>级别</th>
            <th>手机号</th>
            <th>诊治类别</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="doctor in pagedDoctors" :key="doctor.id">
            <td>
              <img v-if="doctor.image" :src="doctor.image" alt="头像" class="doctor-avatar" />
              <span v-else style="color:#bbb;">无</span>
            </td>
            <td>{{ doctor.name }}</td>
            <td>{{ doctor.age }}</td>
            <td>{{ doctor.gender }}</td>
            <td>{{ doctor.level }}</td>
            <td>{{ doctor.phone }}</td>
            <td>{{ doctor.category }}</td>
            <td>
              <button class="edit-btn" @click="openEditDialog(doctor)">编辑</button>
              <button class="delete-btn" @click="deleteDoctor(doctor.id)">删除</button>
              <button class="reset-btn" @click="resetPassword(doctor)">重置密码</button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
    <div class="pagination">
      <button :disabled="page===1" @click="page--">上一页</button>
      <span>第 {{ page }} 页 / 共 {{ totalPages }} 页</span>
      <button :disabled="page===totalPages" @click="page++">下一页</button>
    </div>

    <!-- 新增/编辑弹窗 -->
    <div v-if="showDialog" class="dialog-mask">
      <div class="dialog">
        <h3>{{ editMode ? '编辑医师' : '新增医师' }}</h3>
        <form @submit.prevent="saveDoctor">
          <label v-if="!editMode">账号：
            <input
              v-model="form.account"
              required
              placeholder="请输入医师账号"
              pattern="^[A-Za-z0-9]{6,20}$"
              maxlength="20"
              @input="validateAccount"
            />
          </label>
          <div v-if="!editMode && accountError" class="error-msg">{{ accountError }}</div>
          <label>姓名：<input v-model="form.name" required /></label>
          <label>年龄：<input v-model.number="form.age" type="number" min="18" max="100" required /></label>
          <label>性别：
            <select v-model="form.gender" required>
              <option value="男">男</option>
              <option value="女">女</option>
            </select>
          </label>
          <label>级别：
            <select v-model="form.level" required>
              <option v-for="level in doctorLevels" :key="level" :value="level">{{ level }}</option>
            </select>
          </label>
          <label>手机号：<input v-model="form.phone" required pattern="^1[3-9]\d{9}$" type="text" /></label>
          <label>诊治类别：
            <select v-model="form.category" required>
              <option v-for="cat in doctorCategories" :key="cat.id" :value="cat.category">{{ cat.category }}</option>
            </select>
          </label>
          <!-- 图片上传区域 -->
          <template v-if="editMode">
            <label>头像：
              <input type="file" accept="image/*" @change="onImageChange" />
            </label>
            <div v-if="form.image" style="text-align:center;margin-bottom:10px;">
              <img :src="form.image" alt="头像预览" style="width:60px;height:60px;border-radius:50%;object-fit:cover;box-shadow:0 2px 8px #eee;" />
            </div>
          </template>
          <div class="dialog-actions">
            <button type="submit" :disabled="loading">{{ loading ? '保存中...' : '保存' }}</button>
            <button type="button" @click="closeDialog">取消</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import axios from 'axios';

const props = defineProps({
  userRole: {
    type: String,
    default: 'user'
  }
});

const doctors = ref([]);
const loading = ref(false);
const message = ref('');
const messageType = ref('');

// 从localStorage获取级别和诊治类别
const doctorLevels = ref(['实习医师','住院医师', '主治医师', '副主任医师','主任医师']);
const doctorCategories = ref([]);

onMounted(() => {
  // 从localStorage加载数据
  const savedLevels = localStorage.getItem('doctorLevels');
  const savedCategories = localStorage.getItem('doctorCategories');
  
  if (savedLevels) doctorLevels.value = JSON.parse(savedLevels);
  if (savedCategories) doctorCategories.value = JSON.parse(savedCategories);
  
  fetchDoctorCategories();
  fetchDoctors();
});

const filter = ref({ name: '', gender: '', level: '', category: '' });
const filteredDoctors = computed(() => {
  return doctors.value.filter(d => {
    return (
      (!filter.value.name || d.name.includes(filter.value.name)) &&
      (!filter.value.gender || d.gender === filter.value.gender) &&
      (!filter.value.level || d.level === filter.value.level) &&
      (!filter.value.category || d.category === filter.value.category)
    );
  });
});

const page = ref(1);
const pageSize = 10;
const totalPages = computed(() => Math.ceil(filteredDoctors.value.length / pageSize));
const pagedDoctors = computed(() => {
  const start = (page.value - 1) * pageSize;
  return filteredDoctors.value.slice(start, start + pageSize);
});

const showDialog = ref(false);
const editMode = ref(false);
const form = ref({ id: null, account: '', name: '', age: '', gender: '男', level: '普通医师', phone: '', category: '', image: '' });
const accountError = ref('');

// 显示消息提示
function showMessage(msg, type = 'success') {
  message.value = msg;
  messageType.value = type;
  setTimeout(() => {
    message.value = '';
    messageType.value = '';
  }, 3000);
}

// 获取所有医生
async function fetchDoctors() {
  try {
    loading.value = true;
    const storedToken = localStorage.getItem('token');
    const response = await axios.get('http://47.93.134.56:8800/doctor/get/all', {
      headers: {
        'token': storedToken
      }
    });
    if (response.data.code === 200) {
      doctors.value = response.data.data || [];
    } else {
      showMessage(response.data.msg || '获取医生列表失败', 'error');
    }
  } catch (error) {
    showMessage(error.response?.data?.msg || '网络错误', 'error');
  } finally {
    loading.value = false;
  }
}

// 获取诊治类别
async function fetchDoctorCategories() {
  try {
    const storedToken = localStorage.getItem('token');
    const response = await axios.get('http://47.93.134.56:8800/doctor/get/categories', {
      headers: { 'token': storedToken }
    });
    if (response.data.code === 200) {
      doctorCategories.value = response.data.data;
    } else {
      showMessage(response.data.msg || '获取诊治类别失败', 'error');
    }
  } catch (error) {
    showMessage(error.response?.data?.msg || '网络错误', 'error');
  }
}

// 添加医生
async function addDoctor(doctorData) {
  try {
    loading.value = true;
    const storedToken = localStorage.getItem('token');
    // 只提交后端需要的字段
    const submitData = {
      account: doctorData.account,
      name: doctorData.name,
      image: doctorData.image,
      age: doctorData.age,
      gender: doctorData.gender,
      level: doctorData.level,
      phone: doctorData.phone,
      category: doctorData.category
    };
    const response = await axios.post('http://47.93.134.56:8800/doctor/add', submitData, {
      headers: { 'token': storedToken }
    });
    if (response.data.code === 200) {
      // 后端返回数据不含account，需补全
      const newDoctor = { ...response.data.data, account: doctorData.account };
      showMessage(response.data.msg || '添加医生成功');
      doctors.value.push(newDoctor);
      return true;
    } else {
      showMessage(response.data.msg || '添加医生失败', 'error');
      return false;
    }
  } catch (error) {
    showMessage(error.response?.data?.msg || '网络错误', 'error');
    return false;
  } finally {
    loading.value = false;
  }
}

// 更新医生
async function updateDoctor(doctorData) {
  try {
    loading.value = true;
    const storedToken = localStorage.getItem('token');
    const response = await axios.post('http://47.93.134.56:8800/doctor/update', doctorData, {
      headers: {
        'token': storedToken
      }
    });
    if (response.data.code === 200) {
      showMessage(response.data.msg || '更新医生成功');
      await fetchDoctors(); // 重新获取列表
      return true;
    } else {
      showMessage(response.data.msg || '更新医生失败', 'error');
      return false;
    }
  } catch (error) {
    showMessage(error.response?.data?.msg || '网络错误', 'error');
    return false;
  } finally {
    loading.value = false;
  }
}

// 删除医生
async function deleteDoctorById(id) {
  try {
    loading.value = true;
    const storedToken = localStorage.getItem('token');
    const response = await axios.delete(`http://47.93.134.56:8800/doctor/delete/${id}`, {
      headers: {
        'token': storedToken
      }
    });
    if (response.data.code === 200) {
      showMessage(response.data.msg || '删除医生成功');
      await fetchDoctors(); // 重新获取列表
      return true;
    } else {
      showMessage(response.data.msg || '删除医生失败', 'error');
      return false;
    }
  } catch (error) {
    showMessage(error.response?.data?.msg || '网络错误', 'error');
    return false;
  } finally {
    loading.value = false;
  }
}

function openAddDialog() {
  editMode.value = false;
  form.value = { id: null, account: '', name: '', age: '', gender: '男', level: '普通医师', phone: '', category: '', image: '' };
  showDialog.value = true;
}
function openEditDialog(doctor) {
  editMode.value = true;
  form.value = { ...doctor };
  showDialog.value = true;
}
function closeDialog() {
  showDialog.value = false;
}
async function saveDoctor() {
  // 只校验账号（新增时）、姓名、年龄、手机号，头像可为空
  if ((!editMode.value && !form.value.account) || !form.value.name || !form.value.age || !form.value.phone || !form.value.level || !form.value.gender || !form.value.category) {
    showMessage('请填写完整信息', 'error');
    return;
  }
  // 新增时账号格式校验
  if (!editMode.value) {
    const accountPattern = /^[A-Za-z0-9]{6,20}$/;
    if (!accountPattern.test(form.value.account)) {
      accountError.value = '账号只能为6-20位字母或数字';
      return;
    }
  }
  
  // 手机号格式验证
  const phonePattern = /^1[3-9]\d{9}$/;
  if (!phonePattern.test(form.value.phone)) {
    showMessage('请输入正确的手机号格式', 'error');
    return;
  }
  
  // 年龄验证
  if (form.value.age < 18 || form.value.age > 100) {
    showMessage('年龄必须在18-100之间', 'error');
    return;
  }
  
  let success = false;
  if (editMode.value) {
    success = await updateDoctor(form.value);
  } else {
    success = await addDoctor(form.value);
  }
  
  if (success) {
    showDialog.value = false;
  }
}
async function deleteDoctor(id) {
  if (confirm('确定要删除该医师吗？')) {
    await deleteDoctorById(id);
  }
}

// 重置密码
async function resetPassword(doctor) {
  if (!doctor || !doctor.id) return;
  try {
    loading.value = true;
    const storedToken = localStorage.getItem('token');
    const response = await axios.post(`http://47.93.134.56:8800/user/resetPassword/${doctor.id}`, {}, {
      headers: { 'token': storedToken }
    });
    if (response.data.code === 200) {
      showMessage(response.data.msg || '重置密码成功');
    } else {
      showMessage(response.data.msg || '重置失败', 'error');
    }
  } catch (error) {
    showMessage(error.response?.data?.msg || '网络错误', 'error');
  } finally {
    loading.value = false;
  }
}

function applyFilter() {
  page.value = 1;
}
function resetFilter() {
  filter.value = { name: '', gender: '', level: '', category: '' };
  page.value = 1;
}

// 新增/编辑时支持图片上传，图片可为空。上传接口按新增/编辑区分id，上传成功自动填充form.image并预览。
function getUploadId() {
  // 新增时用account，编辑时用id
  return editMode.value ? form.value.id : form.value.account
}
async function onImageChange(e) {
  const file = e.target.files[0]
  if (!file) return
  const id = getUploadId()
  if (!id) {
    showMessage('请先填写账号（新增）或保存后再上传头像', 'error')
    return
  }
  const formData = new FormData()
  formData.append('file', file)
  try {
    loading.value = true
    const storedToken = localStorage.getItem('token')
    const res = await axios.post(`http://47.93.134.56:8800/common/upload/${id}`, formData, {
      headers: { 'Content-Type': 'multipart/form-data', 'token': storedToken }
    })
    if (res.data.code === 200 && res.data.data) {
      form.value.image = res.data.data
      showMessage('头像上传成功')
    } else {
      showMessage(res.data.msg || '头像上传失败', 'error')
    }
  } catch (err) {
    showMessage('头像上传失败', 'error')
  } finally {
    loading.value = false
  }
}

// 实时校验账号输入，输入时调用 validateAccount 方法。
function validateAccount() {
  if (!form.value.account) {
    accountError.value = '账号不能为空';
  } else if (!/^[A-Za-z0-9]{6,20}$/.test(form.value.account)) {
    accountError.value = '账号只能为6-20位字母或数字';
  } else {
    accountError.value = '';
  }
}
</script>

<style scoped>
.doctor-management-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.doctor-table-scroll {
  flex: 1 1 auto;
  min-height: 0;
  max-height: none;
  overflow-y: auto;
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0,0,0,0.04);
}
.doctor-table-scroll::-webkit-scrollbar {
  width: 8px;
  background: #f4f7f9;
  border-radius: 8px;
}
.doctor-table-scroll::-webkit-scrollbar-thumb {
  background: #dbeafe;
  border-radius: 8px;
}
.doctor-table-scroll:hover::-webkit-scrollbar-thumb {
  background: #b6d4fe;
}
.doctor-table thead th {
  position: sticky;
  top: 0;
  z-index: 2;
  background: #f4f7f9;
}
.doctor-table button {
  margin: 0 4px;
  padding: 4px 10px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.95rem;
}
.edit-btn {
  background-color: #d4edda;
  color: #155724;
  border: 1px solid #c3e6cb;
}
.edit-btn:hover {
  background-color: #c3e6cb;
  color: #155724;
}
.delete-btn {
  background-color: #f8d7da;
  color: #721c24;
  border: 1px solid #f5c6cb;
}
.delete-btn:hover {
  background-color: #f5c6cb;
  color: #721c24;
}
.reset-btn {
  background-color: #fffbe6;
  color: #b8860b;
  border: 1px solid #ffe58f;
}
.reset-btn:hover {
  background-color: #ffe58f;
  color: #b8860b;
}

.doctor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.add-btn {
  background: #3498db;
  color: #fff;
  border: none;
  padding: 8px 18px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 1rem;
}
.add-btn:hover {
  background: #217dbb;
}
.doctor-table {
  width: 100%;
  border-collapse: collapse;
  margin-bottom: 20px;
}
.doctor-table th, .doctor-table td {
  border: 1px solid #e0e0e0;
  padding: 10px 8px;
  text-align: center;
}
.doctor-table th {
  background: #f4f7f9;
}
.doctor-table tr:nth-child(even) {
  background: #fafbfc;
}
.pagination {
  display: flex;
  align-items: center;
  gap: 16px;
  justify-content: flex-end;
}
.dialog-mask {
  position: fixed;
  left: 0; top: 0; right: 0; bottom: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

.dialog {
  background: white;
  border-radius: 12px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
  width: 90%;
  max-width: 500px;
  max-height: 80vh;
  overflow-y: auto;
  animation: slideIn 0.3s ease;
  border: 1px solid #e0e0e0;
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(-50px) scale(0.95);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

.dialog h3 {
  margin: 0 0 25px 0;
  font-size: 1.4rem;
  font-weight: 600;
  color: #2c3e50;
  text-align: center;
  padding-bottom: 15px;
  border-bottom: 2px solid #3498db;
}

.dialog form {
  padding: 0 20px 20px 20px;
}

.dialog label {
  display: block;
  margin-bottom: 8px;
  font-size: 0.95rem;
  font-weight: 500;
  color: #34495e;
}

.dialog input, .dialog select {
  width: 100%;
  padding: 12px 15px;
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  font-size: 1rem;
  transition: all 0.3s ease;
  box-sizing: border-box;
  background: #fafbfc;
}

.dialog input:focus, .dialog select:focus {
  outline: none;
  border-color: #3498db;
  background: white;
  box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.1);
}

.dialog-actions {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #e0e0e0;
}

.dialog-actions button {
  padding: 12px 30px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 1rem;
  font-weight: 500;
  transition: all 0.3s ease;
  min-width: 100px;
}

.dialog-actions button[type="submit"] {
  background: linear-gradient(135deg, #3498db, #2980b9);
  color: white;
  box-shadow: 0 4px 15px rgba(52, 152, 219, 0.3);
}

.dialog-actions button[type="submit"]:hover {
  background: linear-gradient(135deg, #2980b9, #1f5f8b);
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(52, 152, 219, 0.4);
}

.dialog-actions button[type="button"] {
  background: linear-gradient(135deg, #95a5a6, #7f8c8d);
  color: white;
  box-shadow: 0 4px 15px rgba(149, 165, 166, 0.3);
}

.dialog-actions button[type="button"]:hover {
  background: linear-gradient(135deg, #7f8c8d, #6c7b7d);
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(149, 165, 166, 0.4);
}

.filter-bar {
  display: flex;
  gap: 12px;
  margin-bottom: 18px;
  align-items: center;
}
.filter-input, .filter-select {
  padding: 6px 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  font-size: 1rem;
}
.filter-btn {
  background: #3498db;
  color: #fff;
  border: none;
  padding: 6px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 1rem;
}
.filter-btn:hover {
  background: #217dbb;
}
.error-msg {
  color: #e74c3c;
  font-size: 0.95rem;
  margin-bottom: 8px;
  margin-left: 2px;
}

/* 禁用状态 */
.dialog-actions button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.no-permission {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  font-size: 1.3rem;
  color: #e74c3c;
  background: #fff0f0;
  border-radius: 10px;
}

.message {
  padding: 12px 16px;
  margin-bottom: 15px;
  border-radius: 6px;
  font-size: 0.9rem;
  font-weight: 500;
}
.message.success {
  background: #d4edda;
  color: #155724;
  border: 1px solid #c3e6cb;
}
.message.error {
  background: #f8d7da;
  color: #721c24;
  border: 1px solid #f5c6cb;
}

.doctor-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
  border: 1.5px solid #e0e0e0;
  background: #f4f7f9;
  box-shadow: 0 2px 8px rgba(52,152,219,0.08);
}
</style>